package com.itheima.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.goods.pojo.Spec;
import com.itheima.goods.service.SpecService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author cai xu dong
 * @date 2021/5/9 20:17
 */
@RestController
@RequestMapping("spec")
public class SpecController {
    @Autowired
    private SpecService specService;

    @GetMapping
    public Result findAll() {
        List<Spec> list = specService.list();
        return new Result(true, 2000, "查询成功", list);
    }

    @PostMapping
    public Result add(@RequestBody Spec s) {
        specService.save(s);
        return new Result(true, 2000, "增加成功");
    }

    @GetMapping("search/{page}/{size}")
    public Result search(@PathVariable("page") Long current, @PathVariable("size") Long size) {
        Page<Spec> Page = new Page<>(current, size);
        specService.page(Page);
        return new Result(true, 2000, "查询成功", Page);
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable int id) {
        Spec spec = specService.getById(id);
        return new Result(true, 20000, "查询成功", spec);
    }

    @PostMapping("search2/{page}/{size}")
    public Result search2(@PathVariable("page") Long current, @PathVariable("size") Long size,
                          @RequestBody Map<String, String> searchMap) {
        Page<Spec> pages = new Page<>(current, size);
        LambdaQueryWrapper<Spec> wrapper = Wrappers.<Spec>lambdaQuery();
        wrapper.eq(Spec::getId, searchMap.get("id"));
        wrapper.like(Spec::getOptions, searchMap.get("options"));
        Page<Spec> page = specService.page(pages, wrapper);
        return new Result(true, 20000, "查询成功", page);
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable("id") int id, @RequestBody Spec spec) {
        LambdaQueryWrapper<Spec> wrapper = Wrappers.<Spec>lambdaQuery();
        LambdaQueryWrapper<Spec> eq = wrapper.eq(Spec::getId, id);
        boolean update = specService.update(spec, eq);
        return new Result(true, 20000, "更新成功", update);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") int id) {
        specService.removeById(id);
        return new Result(true, 20000, "删除成功");
    }
}
